let fs = require("fs");


function filter_line(exml = "")
{
    return exml.split("\n\t");
}


function find(lines = [],target_str = "")
{
    for(let i in lines)
    {
        if(lines[i].search(target_str) != -1)
        {
            let len = target_str.length;
            let startIdx = lines[i].search(target_str);
            let tail = lines[i].slice(startIdx +len);
            let endIdx = tail.search("\"");
            if(endIdx != -1)
            {
                // 检测小数点后边
                let str = lines[i].slice(startIdx+ len,startIdx + len + endIdx);
                let point_idx = str.indexOf('.') ;
                if(point_idx != -1)
                {
                    let point_tail = str.slice( point_idx );
                    if(point_tail.length > 2)
                    {
                        // todo 替换小数点

                        // 85 66666666666
                        let split_Str = str.split('.');
                        // 85.6
                        let new_Str = split_Str[0] + "." + split_Str[1][0];

                        lines[i] = lines[i].replace(str,new_Str);
                    }
                }
            }
        }   
    }
}

function linesToStr(lines = [])
{
    let str = "";
    for(let i = 0 ;i< lines.length ;i++)
    {
        if(i == lines.length - 1)
        {
            str += lines[i];
        }
        else
        {
            str += lines[i] + "\n\t";
        }
    }
    return str;
}


function exml_replace(path)
{
    let exml = fs.readFileSync(path,'utf-8'); //read("C:\\Users\\Administrator\\Documents\\qp_client\\resource\\game_skins\\scene\\G_Sign.exml");

    let lines = filter_line(exml);

    find(lines,"x=\"");
    find(lines,"x.1=\"");
    find(lines,"x.2=\"");
    find(lines,"x.3=\"");
    find(lines,"x.4=\"");
    find(lines,"x.5=\"");
    find(lines,"x.6=\"");
    
    find(lines,"y=\"");
    find(lines,"y.1=\"");
    find(lines,"y.2=\"");
    find(lines,"y.3=\"");
    find(lines,"y.4=\"");
    find(lines,"y.5=\"");
    find(lines,"y.6=\"");

    let new_exml = linesToStr(lines);

    fs.writeFileSync(path,new_exml,'utf-8');
}

function isExml(str = "")
{
    return str.search(".exml") != -1;
}


let root = "./resource/game_skins/";

function dir(p_root)
{
    let skins_path = fs.readdirSync(p_root);
    skins_path.forEach((p,index) =>
    {
        let new_p = p_root + "/" + p;
        console.log(">>>> 检索路径 : " +new_p);
        let sta = fs.statSync(new_p);
        if(sta.isDirectory())
        {
            dir(new_p);
        }
        else
        {
            if( isExml( new_p ) )
            {
                exml_replace( new_p );
                console.log(">>>> 替换文件 : " +new_p);
            }
            
        }
    });
}

console.log(">>>> 正在搜索文件");
dir(root);
console.log(">>>> 检索完毕");

